package com.zjxh.zjxh.config;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
class CORSFilter implements Filter {
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    HttpServletResponse res = (HttpServletResponse) response;
    HttpServletRequest req = (HttpServletRequest) request;
    res.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
    // res.addHeader("Access-Control-Allow-Credentials","true");// 正式环境去掉这个
    res.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH");
    res.setHeader(
        "Access-Control-Allow-Headers",
        "Uuid,User-Id,Platform,token,Origin,User-Agent,Token, X-Requested-With, Content-Type, Accept");
    res.addHeader("Access-Control-Expose-Headers", "user-id, UUID, platform");
    if (((HttpServletRequest) request).getMethod().equals("OPTIONS")) {
      response.getWriter().println("ok");
      return;
    }
    chain.doFilter(request, response);
  }

  @Override
  public void destroy() {}

  @Override
  public void init(FilterConfig filterConfig) throws ServletException {}
}
